﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gfw.Infrastructure.Account;
using Gfw.Infrastructure.ExceptionImpl;
using Gfw.Infrastructure.Facilities;
using Gfw.Models.Stock;
using Gfw.Repositories.Account;
using Gfw.Repositories.Admin;

namespace Gfw.Infrastructure.Stock.Facilities
{
    /// <summary>
    /// 股票卖出的利润分配
    /// </summary>
    public class StockAllot : IFacility
    {

        private const decimal RecommandDevidendsRatio = 0.05M;
        private const decimal TaxRatio = 0.08M;


        private StkUseraccount _stockAccount;
        private decimal _count;

        private decimal _recommand;
        private decimal _indival;
        private decimal _taxcount;

        public StockAllot(StkUseraccount stockAccount, decimal count)
        {
            _count = count;
            _stockAccount = stockAccount;
        }

        public void Execute(Repository.UnitOfWork unitOfWork = null)
        {
            if (unitOfWork == null)
                throw new GfwTransactionInvalidException("该功能不能作为原子事务。");

            UsrUserRepository userRep = new UsrUserRepository();
            var user = userRep.Get(_stockAccount.UserId);

            _recommand = Math.Round(_count*RecommandDevidendsRatio, 2);
            _taxcount = Math.Round(_count*TaxRatio, 2);
            _indival = _count - _recommand - _taxcount;

            string awardSerialNo = Guid.NewGuid().ToString();
            string taxNo = Guid.NewGuid().ToString();

            //推荐人分红
            Dividends dividends = new Dividends(user.Recommender, _recommand);
            dividends.Execute(unitOfWork);

            //公司上税
            Tax at = new Tax(_stockAccount.UserId, _taxcount, awardSerialNo, taxNo);
            at.Execute(unitOfWork);

            //分配到个人帐户
            StockProfit allot = new StockProfit(_stockAccount, _indival, awardSerialNo, taxNo);
            allot.Execute(unitOfWork);

            //股票销售收入，纳入动态奖金计算
            //插入动态奖金分配表
            ActUserDynamicawardRepository userAwardRepository = new ActUserDynamicawardRepository();
            userAwardRepository.AddAward(_stockAccount.UserId, (int)UserTradeTypeEnum.Sell_Stock, _count, _indival, AllTax(),
                                         awardSerialNo, unitOfWork);

        }

        public decimal AllTax()
        {
            return _recommand + _taxcount;
        }

        public decimal Income()
        {
            return _indival;
        }
    }
}
